package com.jm.bishe.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenUtil {

    private static final String CLAIM_KEY_USERNAME="zhanan";
    private static final String CLAIM_KEY_CREATED="created";
    //令牌
    private static final String secret = "tiezhu";
    //过期时间 15天
    private static final int expiration = 15;

    /**
     * 生成token
     * @param map
     * @return
     */
    private static String getToken(Map<String,String> map){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,expiration);

        JWTCreator.Builder builder = JWT.create();

        //lambda 遍历map写进荷载
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });

        String token = builder.withExpiresAt(instance.getTime())//设置过期时间
                .sign(Algorithm.HMAC256(secret));//设置令牌及加密算法

        return token;

    }


    /**
     * 验证token是否合法
     * @param token
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
    }


    public static String getId(String token){
        DecodedJWT decodedJWT = JwtTokenUtil.verify(token);
        return decodedJWT.getClaim("userId").asString();
    }


    public static String getToken(String adminId){
        HashMap<String, String> map = new HashMap<>();
        map.put("userId",adminId);
        return JwtTokenUtil.getToken(map);
    }

}
